package com.example.my_gobang.api;

import com.example.my_gobang.mapper.UserMapper;
import com.example.my_gobang.model.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-19
 * Time:14:25
 */
@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        // 根据username查询数据库
        User user = userMapper.selectByName(username);
        System.out.println("登录用户：" + username);
        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("登录失败！");
            return new User();
        }
        //保存会话
        HttpSession httpSession = req.getSession(true);
        httpSession.setAttribute("user",user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            //注册失败，返回空对象
            return new User();
        }
    }

    @RequestMapping("/userinfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        try {
            HttpSession httpSession = req.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            // 根据这个user对象去数据库中找到最新的数据
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            //获取信息失败，返回空对象
            return new User();
        }
    }
}
